package cn.ruicz.basecore.base;

import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import java.util.List;
import cn.ruicz.basecore.adapter.ViewPagerAdapter;
import cn.ruicz.basecore.bean.ItemPager;

/**
 * cn.ruicz.base.ui.viewpager
 *
 * @author liqq
 * @time 2019/6/11 16:24
 * Remark -------------ViewpagerFragment--------------------------
 */
public abstract class BaseViewPagerFragment<V extends ViewDataBinding,VM extends BaseViewModel> extends BaseFragment<V,VM> {

    protected ViewPagerAdapter adapter;
    protected ViewPager viewPager;
    protected  boolean toChildResult = true;//在使用onFragmentResult时，是否将数据传递到当前显示的子Fragment里


    @Override
    public void init() {
        initViewpager();
        initTabLayout();
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if(toChildResult && adapter.getFragmentList().size() > 0 && viewPager.getCurrentItem() >= 0){
            BaseFragment fragment = adapter.getFragmentList().get(viewPager.getCurrentItem()).itemFragment;
            fragment.onFragmentResult(requestCode, resultCode, data);
        }
    }

    /**
     * 在使用onFragmentResult时，是否将数据传递到当前显示的子Fragment里
     */
    public void setToChildResult(boolean toChildResult){
        this.toChildResult = toChildResult;
    }

    private void initViewpager(){
        adapter = getViewPagerAdapter();
        adapter.setFragmentList(createPagerList());
        viewPager = getViewPager();
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(maxOffscreenPageLimit());
    }

    private void initTabLayout(){
        TabLayout tabs = getTabLayout();
        if(tabs == null) return;
        tabs.setupWithViewPager(viewPager);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabs));
    }

    @NonNull
    public ViewPagerAdapter getViewPagerAdapter(){
        return new ViewPagerAdapter(getChildFragmentManager());
    }

    @NonNull
    protected abstract ViewPager getViewPager();

    protected abstract TabLayout getTabLayout();

    @NonNull
    protected abstract List<ItemPager> createPagerList();

    protected abstract int maxOffscreenPageLimit();
}
